import { getDispatch } from '../dva';

const GoodsSelectTypeEnum = {
  goods: '1',
  platCategory: '2',
  merchant: '3',
  all: '4',
};

function deepClone(v) {
  return JSON.parse(JSON.stringify(v));
}

function buildPaginationRequest({ payload, type, isLast, forceAll }) {
  const dispatch = getDispatch();

  // 请求参数 复制
  const clone = deepClone(payload);

  // 拼接请求结果
  let result = [];

  // 是否有下一页
  let isFinished = false;

  // 当前第几页
  let page = 1;
  const pageSize = 10;

  return async () => {
    // 已结束, 不请求
    if (isFinished) {
      return {
        list: result,
        isFinished,
      };
    }

    // 如果不是最后一个,
    // 表示不需要 分页滚动, 直接按照原有参数请求
    if (forceAll || !isLast) {
      // 请求数据
      const { list, pagination } = await dispatch({
        type,
        payload,
      });

      result = list;
      isFinished = true;

      return {
        list: result,
        pagination,
        isFinished,
      };
    }

    let specialPayload = {
      ...payload,
      page,
      pageSize,
    };

    // 如果是 id 分组, 需要特殊处理
    // 传递的 id + pageSize,  接口不会按照顺序返回
    // 所以 只能 id + page=1, 强制按照顺序返回
    if (payload.type === GoodsSelectTypeEnum.goods) {
      specialPayload = {
        ...specialPayload,
        // 按id 划分
        ids: clone.ids.slice((page - 1) * pageSize, page * pageSize),
        // 每次都请求 ids 的数据, page 为 1
        page: 1,
      };
    }

    // 请求数据
    const res = await dispatch({
      type,
      payload: specialPayload,
    });

    let { list, pagination } = res;

    if (page === 1) {
      result = list;
    } else {
      result = [...result, ...list];
    }

    // 按id 划分 特殊处理
    if (payload.type === GoodsSelectTypeEnum.goods) {
      isFinished = page * pageSize >= clone.ids.length;

      pagination = {
        ...pagination,
        totalCount: clone.ids.length,
      };
    } else {
      isFinished = list.length < pageSize;

      // 超过了后台配置的数量
      if (result.length > clone.pageSize) {
        result = result.slice(0, clone.pageSize);
        isFinished = true;
      }
    }

    console.log('debug for pagination request', {
      realPayload: specialPayload,
      clone,
      result,
      list,
      page,

      isFinished,
    });

    // 下次要下一页了
    page += 1;

    return {
      list: result,
      pagination,
      isFinished,
    };
  };
}

export { buildPaginationRequest };
